using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Threading;
using System.Runtime.InteropServices;
using CourseSync.LibFetcher.Filter;

namespace CourseSync.LibFetcher.Fetcher
{
	public class PageFetcher
	{
		private static CookieContainer _cookie;
		public static System.Net.CookieContainer Cookie
		{
			get
			{
				if (_cookie == null)
					_cookie = new CookieContainer();
				return _cookie;
			}
			//set { _cookie = value; }

		}

		public static Downloader PrepareDownloader(Downloader dl)
		{
			string url = dl.Url;
			string method = dl.Method;
			string post_data = dl.PostData;
			string target_path = dl.Target;
			HttpWebRequest request = BuildRequest(url, method, post_data);
			//do not dispose response here!
			HttpWebResponse response = GetResponse(request);
			dl.Prepare(url, response, target_path);
			return dl;
		}

		public static string GetPage(string url)
		{
			return GetPage(url, "GET", "");
		}

		public static string GetPage(string url, string method, string post_data)
		{
			HttpWebRequest request = BuildRequest(url, method, post_data);
			try
			{
				using (HttpWebResponse response = GetResponse(request))
				{
					using (Stream stream = response.GetResponseStream())
					{
						using (StreamReader reader = new StreamReader(stream))
						{

							string webPage = reader.ReadToEnd();
							return webPage;
						}

					}
				}
			}
			catch
			{
				return string.Empty;
			}
		}
		private static HttpWebRequest BuildRequest(string url, string method, string post_data)
		{
			string postData = post_data;
			HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
			request.CookieContainer = Cookie;
			request.Method = method;
			request.ServicePoint.Expect100Continue = false;
			FakeBrowserDecorator.UseFirefox(request);
			if (request.Method == "POST")
			{
				byte[] data = Encoding.UTF8.GetBytes(postData);
				request.ContentLength = data.Length;
				using (Stream newStream = request.GetRequestStream())
				{
					// Send the data.
					newStream.Write(data, 0, data.Length);
				}
			}
			return request;
		}
		private static HttpWebResponse GetResponse(HttpWebRequest request)
		{
			try
			{
				return (HttpWebResponse)request.GetResponse();
			}
			catch
			{
				return null;
			}
		}

	}
}
